/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package web;

import ejb.UserBeanLocal;
import entities.User;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;

/**
 *
 * @author ervaka
 */
@ManagedBean
@RequestScoped
public class LoginBean {

    private FacesContext context;
    @EJB
    private UserBeanLocal userBean;
    private User user;

    public LoginBean() {
        user = new User();
        context = FacesContext.getCurrentInstance();
    }

    public User getUser() {
        return user;
    }

    public String login() {
        String result = "main";
        User u = userBean.findByCredentials(user.getEmail(), user.getPassword());

        if (u == null) {
            result = "ERROR";
        } else {
            context.getExternalContext().getSessionMap().put("user", u);
            System.out.println("Login succeed!: " + u.getEmail());
        }
        return result;
    }

    public String logout() {
        System.out.println("logout");
        context.getExternalContext().invalidateSession();
        return "logout";
    }
}
